package com.gitee.wsl.collections.iterator

import com.gitee.wsl.func.Function

class FindNextPageIterator<T>(
    private val provider: Function<T?,List<T>>
) : Iterator<List<T>> {

    private var lastEntity: T? = null
    private var entityList: List<T>? = null
    private var eof = false

    override fun hasNext(): Boolean {
        if (eof) return false

        if (entityList != null && !entityList!!.isEmpty()) return true

        entityList = provider(lastEntity)

        if (entityList!!.isEmpty()) {
            eof = true
            return false
        }
        lastEntity = entityList!![entityList!!.size - 1]
        return true
    }

    override fun next(): List<T> {
        if (!hasNext()) throw NoSuchElementException()
        val list = entityList
        this.entityList = null
        return list!!
    }
}